pragma License (GPL);
--
-- drk-bigint-plus.adb
--
-- Copyright (C) 2012 - Thibault BUREL
--
-- This file is part of DRK.BigRat.
--
-- DRK.BigRat is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- DRK.BigRat is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with DRK.BigRat.  If not, see <http://www.gnu.org/licenses/>
--

separate(DRK.BigInt)
function Plus(Left  : in Instance;
              Right : in Instance) return Instance
is
   Result : Instance;

   CL : Digit_List.Cursor := Left.Mantissa.First;
   CR : Digit_List.Cursor := Right.Mantissa.First;

   L, R : Chunck;
   C    : Carry;

   procedure Internal_Addition
   is
   begin

      Result.Mantissa.Append (R + L + C);

      if Chunck'Last - R - C >= L then
         C := 0;
      else
         C := 1;
      end if;

   end Internal_Addition;
   pragma Inline(Internal_Addition);

begin
   C := 0; -- Au debut, pas de retenue
   while CL /= Digit_List.No_Element and
         CR /= Digit_List.No_Element loop

      L := Digit_List.Element(CL);
      R := Digit_List.Element(CR);

      Internal_Addition;

      CL := Digit_List.Next (CL);
      CR := Digit_List.Next (CR);

   end loop;

   -- Quel membre a encore des elements dans sa mantisse
   if CL = Digit_List.No_Element then
      CL := CR;
   end if;

   R := 0;
   while CL /= Digit_List.No_Element loop
      L := Digit_List.Element(CL);

      Internal_Addition;

      CL := Digit_List.Next (CL);

   end loop;

   -- Ne pas oublier la derniere retenue.
   if C /= 0 then

      Result.Mantissa.Append(1);

   end if;

   return Result;

end Plus;

